﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

using Microsoft.Win32;
using StProxyHelper;
using StProxyHelper.Entity;
using System.Threading;

namespace StProxy
{
    public partial class frmMain : Form
    {
        DataTable dt = new DataTable();
        delegate void DelegateTestProxy();

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }   

        /// <summary>
        /// 获取代理信息
        /// </summary>
        /// <returns></returns>
        private string GetProxyInfo()
        {
            int rowIndex = this.dgvProxyList.CurrentRow.Index;
            return this.dgvProxyList.Rows[rowIndex].Cells[0].Value.ToString() + ":" + this.dgvProxyList.Rows[rowIndex].Cells[1].Value.ToString();
        }

        /// <summary>
        /// 读取代理数据
        /// </summary>
        private void LoadData()
        {
            DataTable dt = new DataTable();
            ProxyHelper proxyHelper = new ProxyHelper();
            dt = proxyHelper.GetProxyListTable();
            bindGrid(dt);
            this.tsslStatus.Text = "本软件提供的HTTP代理服务器均经过验证，每10分钟自动更新一次最新通过验证的IP!";
        }

        private void bindGrid(DataTable dt)
        {
            delegageBindGrid dbg = new delegageBindGrid(this.setGrid);
            this.Invoke(dbg, new object[] { dt });
        }

        private void setGrid(DataTable dt)
        {
            this.dgvProxyList.DataSource = dt;
        }

        delegate void delegageBindGrid(DataTable dt);

        private void tsmiReadData_Click(object sender, EventArgs e)
        {
            try
            {
                Thread thread = new Thread(new ThreadStart(this.LoadThis));
                thread.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadThis()
        {
            this.tsslStatus.Text = "数据加载中，请稍候...";
            SetCursor(Cursors.AppStarting);
            LoadData();
            SetCursor(Cursors.Default);
        }

        private void SetCursor(Cursor cursor)
        {
            delegateSetCursor dsc = new delegateSetCursor(this.SS);
            this.Invoke(dsc, new object[] { cursor });
        }

        private void SS(Cursor c)
        {
            this.Cursor = c;
        }

        delegate void delegateSetCursor(Cursor c);


        /// <summary>
        /// 复制到粘贴板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiCopy_Click(object sender, EventArgs e)
        {
            string strProxyServer = GetProxyInfo();
            Clipboard.SetText(strProxyServer);
            this.tsslStatus.Text = strProxyServer + "已成功复制！";
        }

        /// <summary>
        /// 右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvProxyList_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.RowIndex > -1)
            {
                this.dgvProxyList.CurrentCell = this.dgvProxyList.Rows[e.RowIndex].Cells[e.ColumnIndex];
                this.cmsProxyMenu.Show(Control.MousePosition);
            }
        }

        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            Form fAbout = new frmAbout();
            fAbout.ShowDialog();
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiTest_Click(object sender, EventArgs e)
        {
          

            try
            {
                Thread thread = new Thread(new ThreadStart(this.TestProxy));
                thread.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void DelegateTestProxyRun()
        {
            DelegateTestProxy dt = new DelegateTestProxy(TestProxy);
            this.BeginInvoke(dt);
        }

        private void TestProxy()
        {
            try
            {
                ProxyHelper proxyHelper = new ProxyHelper();
                string proxyHost = GetProxyInfo();

                this.tsslStatus.Text = "正在测试代理服务器" + proxyHost + ",请稍后...";

                if (proxyHelper.TestProxy(proxyHost))
                {
                    this.tsslStatus.Text = "连接代理服务器" + proxyHost + "成功，可正常使用！";
                }
                else
                {
                    this.tsslStatus.Text = "连接代理服务器" + proxyHost + "失败，无法使用！";
                }
            }
            catch (Exception ex)
            {
                this.tsslStatus.Text = ex.Message;
            }
        }

        private void doesntWork()
        {
            MessageBox.Show("对不起，次功能尚未开发，尽情期待！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void tsmiStWapBrowser_Click(object sender, EventArgs e)
        {
            doesntWork();
        }


        private void SetIEProxy(string ProxyServer, int EnableProxy)
        {
            //打开注册表键 
            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);

            //设置代理可用 
            rk.SetValue("ProxyEnable", EnableProxy);

            if (!ProxyServer.Equals("") && EnableProxy == 1)
            {
                //设置代理IP和端口 
                rk.SetValue("ProxyServer", ProxyServer);

                if (DialogResult.Yes == MessageBox.Show("设置IE代理成功！你是否要通过http://ip.sooot.cn查看当前IP地址属地？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
                {
                    Process.Start("http://ip.sooot.cn");
                }
            }

            if (EnableProxy == 0)
            {
                MessageBox.Show("已成功取消IE代理设置，请关闭IE重新打开！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            rk.Close();
        }

        /// <summary>
        /// 设置IE代理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiIE_Click(object sender, EventArgs e)
        {
            SetIEProxy(GetProxyInfo(),1);
        }

        
        /// <summary>
        /// 取消IE代理设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiFobiddenProxy_Click(object sender, EventArgs e)
        {
            SetIEProxy("", 0);
        }

        /// <summary>
        /// 取消IE代理设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiCancelProxy_Click(object sender, EventArgs e)
        {
            SetIEProxy("", 0);
        }


        private void SetIESupportWap()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Classes\MIME\Database\Content Type\text/vnd.wap.wml", true);

            if (rk == null)
            {
                rk = Registry.CurrentUser.CreateSubKey(@"Software\Classes\MIME\Database\Content Type\text/vnd.wap.wml");
            }

            //设置代理可用 
            rk.SetValue("CLSID", "{25336920-03F9-11cf-8FD0-00AA00686F13}");

            rk.Close();
        }

        private void tsmiSetIEsupportWap_Click(object sender, EventArgs e)
        {
            SetIESupportWap();

            if(DialogResult.Yes == MessageBox.Show("设置成功，是否要马上访问速特WAP站点看看效果？","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Information))
            {
                Process.Start("http://wap.sooot.cn");
            }
        }

        private void tsmiOnlineHelp_Click(object sender, EventArgs e)
        {
            Process.Start("http://wap.sooot.cn");
        }

        private void tsmiUpdate_Click(object sender, EventArgs e)
        {
            Process.Start("http://wap.sooot.cn");
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.dgvProxyList.AutoGenerateColumns = false;
        }
    }
}
